package com.xcesys.extras.remoting.system.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xcesys.extras.core.service.ICrudService;
import com.xcesys.extras.dataobject.system.Resource;
import com.xcesys.extras.dataobject.system.Role;
import com.xcesys.extras.dataobject.system.User;
import com.xcesys.extras.model.TsResource;
import com.xcesys.extras.model.TsRole;
import com.xcesys.extras.model.TsUser;
import com.xcesys.extras.remoting.BaseRemotingServiceCrudImpl;
import com.xcesys.extras.remoting.system.RRoleService;
import com.xcesys.extras.system.service.TsRoleService;

@Service("RRoleService")
public class RRoleSerivceImp extends BaseRemotingServiceCrudImpl<Role, TsRole>
		implements RRoleService {

	@Autowired
	private TsRoleService service;

	@Override
	public void addResourcestoRole(Long roleId, List<Long> resourceIds) {
		service.addResourcesToRole(roleId, resourceIds);

	}

	@Override
	public void addUsersToRole(Long roleId, List<Long> userIds) {
		service.addUsersToRole(roleId, userIds);
	}

	@Override
	public Collection<Resource> findResoucesInRole(Long roleId) {
		TsRole role = service.getById(roleId);
		Set<TsResource> resources = role.getTsResources();
		return fromModel(Resource.class, resources);
	}

	@Override
	public List<Resource> findResoucesInRoles(String[] roleNames) {
		List<TsRole> roles = service.findByName(roleNames);
		List<Resource> ress = new ArrayList<Resource>();
		for (TsRole role : roles) {
			Collection<Resource> res = fromModel(Resource.class,
					role.getTsResources());
			if (res != null && !res.isEmpty()) {
				ress.addAll(res);
			}
		}
		return ress;
	}

	@Override
	public Collection<User> findUsersInRole(Long roleId) {
		TsRole role = service.getById(roleId);
		Set<TsUser> users = role.getTsUsers();
		return fromModel(User.class, users);
	}

	@Override
	protected ICrudService<TsRole> getCrudService() {
		return service;
	}

	@Override
	public void removeResourcesFromRole(Long roleId, List<Long> resourceIds) {
		service.removeResourcesFromRole(roleId, resourceIds);
	}
}
